package com.thd.springboot.framework.exceptions;

import com.thd.springboot.framework.model.Message;
import com.thd.springboot.framework.utils.MessageUtils;
import lombok.Data;
import org.slf4j.helpers.MessageFormatter;

/**
 * 业务异常基类
 *
 * @author lilong10
 * @date 2019/03/19 16:41
 * copyright 2019 www.lenovo.com
 */
@Data
public class BasicException extends RuntimeException {

    private String code;
    private String msg;
    private Object[] msgArgs;

    public BasicException(String msg) {
        super(msg);
        this.code = Message.ERROR_DEFAULT_CODE;
        this.msg = msg;
    }

    public BasicException(String code, String msg) {
        super(msg);
        this.code = code;
        this.msg = msg;
    }

    public BasicException(String code, String msg, Throwable t) {
        super(msg, t);
        this.code = code;
        this.msg = msg;
    }


    /**
     * 追加参数
     *
     * @param msgArgs
     * @return
     */
    public BasicException addArgs(Object... msgArgs) {
        this.setMsgArgs(msgArgs);
        return this;
    }

    /**
     * 返回消息，并追加参数
     *
     * @return
     */
    @Override
    public String getMessage() {
        if (msgArgs != null && msgArgs.length > 0) {
            return MessageFormatter.arrayFormat(msg, msgArgs).getMessage();
        }
        return super.getMessage();
    }

    public static void throwBasicExceptionForI18n(String message,Object... obj){
        throw new BasicException(MessageUtils.message(message,obj));
    }
    public static void throwBasicException(String message){
        throw new BasicException(message);
    }

}
